<?php

namespace app\controller\api;

use app\core\ApiController;
use app\core\Request;
use app\service\IncomeService;
use app\service\MemberService;
use app\service\OrderService;
use app\service\SettingsService;
use app\service\SmsService;
use app\service\TeamIncomeService;

class Member extends ApiController
{
    public function reg()
    {
        $data = input('post.');
        MemberService::invoke()->save($data);
        $this->response->success(true);
    }

    public function login()
    {
        $mobile = input('post.mobile');
        $password = input('post.password');
        $memberService = MemberService::invoke();
        $token = $memberService->login($mobile, $password);
        $this->response->success(['token' => $token], "登录成功");
    }

    /**
     * 注册获取手机验证码
     */
    public function getCode()
    {
        $mobile = input('post.mobile');
        $memberInfo = \app\model\Member::where([
            'mobile' => $mobile
        ])->find();
        if ($memberInfo) {
            $this->response->error('该号码已注册');
        }
        $data = MemberService::invoke()->getCode($mobile);
        $time = time() - 60;
        if ($data && $data['time'] > $time) {
            $this->response->error('请稍后获取验证码');
        }
        $code = rand(100000, 999999);
        SmsService::sendSms($mobile, $code);
        MemberService::invoke()->saveCode($code, $mobile);
        $this->response->success(['code' => ''], "获取成功");
    }

    /**
     * 重置密码
     */
    public function reset()
    {
        $password = input('post.password');
        $ret_password = input('post.ret_password');
        if ($password !== $ret_password) {
            $this->response->error('密码不一致');
        }
        $member_id = Request::invoke()->getMember('member_id');
        $memberService = MemberService::invoke();
        $memberService->savePassword($password, $member_id);
        $this->response->success([], "更新成功");
    }

    /**
     * 退出登录
     */
    public function loginOut()
    {
        $member_id = Request::invoke()->getMember('member_id');
        MemberService::invoke()->delToken($member_id);
        $this->response->success([], "退出登录成功");
    }

    /**
     * 注销账户
     */
    public function del()
    {
        $member_id = Request::invoke()->getMember('member_id');
        MemberService::invoke()->del($member_id);
        $this->response->success(true);
    }

    /**
     * 获取邀请码
     */
    public function getInviteCode()
    {
        $invite_code = Request::invoke()->getMember('invite_code');
        $data['invite_code'] = $invite_code;
        $this->response->success($data, '');
    }

    /**
     * 实名认证
     */
    public function checkRealname()
    {
        $member_id = Request::invoke()->getMember('member_id');
        $data = input('post.');
        MemberService::invoke()->saveMemberInfo($data, $member_id);
        $this->response->success([], "成功");
    }

    /**
     * 获取实名认证
     */
    public function getRealname()
    {
        $member_id = Request::invoke()->getMember('member_id');
        $data = MemberService::invoke()->findMemberInfo($member_id);
        $this->response->success($data, "成功");
    }

    /**
     * 我的团队
     */
    public function myTeam()
    {
        $member_id = Request::invoke()->getMember('member_id');
        $page = input('get.page', 1);
        $limit = input('get.limit', 10);
        $searchQuery = input('get.', []);
        $searchQuery['member_id'] = $member_id;
        $list = MemberService::invoke()->getTeamList($page, $limit, $searchQuery);
        $this->response->success($list);
    }

    /**
     * 获取个人主页佣金等数据
     */
    public function home()
    {
        $member_id = Request::invoke()->getMember('member_id');
        $memberInfo = Request::invoke()->getMember();
        $member_num = MemberService::invoke()->getMemberNum($member_id);
        $commission = IncomeService::invoke()->getCommission($member_id);
        $order_amount = OrderService::invoke()->getOrderAmount($member_id);
        $parentMember = \app\model\Member::where(['member_id' => $memberInfo['pid']])->find();
        $memberInfo = \app\model\Member::where(['member_id' => $member_id])->find();
        if ($parentMember) {
            $parentMember = $parentMember->toArray();
        }
        if ($memberInfo) {
            $memberInfo = $memberInfo->toArray();
        }
        $data = [
            'amount' => $memberInfo['amount'] ?: 0.00,
            'pay_amount' => $memberInfo['pay_amount'] ?: 0.00,
            'unset_amount' => $memberInfo['unset_amount'] ?: 0.00,
            'commission' => $commission ?: 0.00,//分销佣金
            'order_amount' => $order_amount ?: 0.00,//分销订单
            'withdrawal_amount' => $memberInfo['pay_amount'] ?: 0.00,//提现明细
            'team_commission' => $memberInfo['team_commission'] ?: 0.00,//团队分红
            'member_num' => $member_num ?: 0,//团队人数
            'nick' => $memberInfo['nick'],
            'avatar' => $memberInfo['avatar'],
            'mobile' => $memberInfo['mobile'],
            'kefu' => '15959771111',
            'pid_nick' => !empty($parentMember['nick']) ? $parentMember['nick'] : '',
            'pid_mobile' => !empty($parentMember['mobile']) ? $parentMember['mobile'] : '',
        ];
        $this->response->success($data);
    }

    /**
     * 我的团队分红
     */
    public function TeamIncomeList()
    {
        $member_id = Request::invoke()->getMember('member_id');
        $page = input('post.page', 1);
        $limit = input('post.limit', 10);
        $searchQuery = input('post.', []);
        $searchQuery['member_id'] = $member_id;
        $list = TeamIncomeService::invoke()->getList($page, $limit, $searchQuery);
        $this->response->success($list);
    }

    /**
     * 分销佣金
     */
    public function IncomeList()
    {
        $member_id = Request::invoke()->getMember('member_id');
        $page = input('get.page', 1);
        $limit = input('get.limit', 10);
        $searchQuery = input('get.', []);
        $searchQuery['member_id'] = $member_id;
        $searchQuery['types'] = [1, 2];
        $list = IncomeService::invoke()->getList($page, $limit, $searchQuery);
        foreach ($list['list'] as $key => $value) {
            $list['list'][$key]['mobile'] = '';
        }
        if ($list['list']) {
            $order_ids = array_column($list['list'], 'order_id');
            $order_list = (new \app\model\Order())->where('order_id', 'in', $order_ids)->field('order_id,member_id')->select()->toArray();
            $member_ids = array_column($order_list, 'member_id');
            $order_list = array_column($order_list, null, 'order_id');
            $member_list = (new \app\model\Member())->where('member_id', 'in', $member_ids)->field('member_id,mobile')->select()->toArray();
            $member_list = array_column($member_list, null, 'member_id');
            foreach ($list['list'] as $key => $value) {
                $list['list'][$key]['mobile'] = $member_list[$order_list[$value['order_id']]['member_id']]['mobile'];
            }
        }

        $this->response->success($list);
    }

    /**
     * 积分列表
     */
    public function pointsList()
    {
        $member_id = Request::invoke()->getMember('member_id');
        $memberInfo = (new \app\model\Member())->where(['member_id' => $member_id])->find();
        $page = input('get.page', 1);
        $limit = input('get.limit', 10);
        $searchQuery = input('get.', []);
        $searchQuery['member_id'] = $member_id;
        $searchQuery['type'] = 3;
        $list = IncomeService::invoke()->getList($page, $limit, $searchQuery);
        foreach ($list['list'] as $key => $value) {
            $list['list'][$key]['mobile'] = '';
        }
        if ($list['list']) {
            $order_ids = array_column($list['list'], 'order_id');
            $order_list = (new \app\model\Order())->where('order_id', 'in', $order_ids)->field('order_id,member_id')->select()->toArray();
            $member_ids = array_column($order_list, 'member_id');
            $order_list = array_column($order_list, null, 'order_id');
            $member_list = (new \app\model\Member())->where('member_id', 'in', $member_ids)->field('member_id,mobile')->select()->toArray();
            $member_list = array_column($member_list, null, 'member_id');
            foreach ($list['list'] as $key => $value) {
                $list['list'][$key]['mobile'] = $member_list[$order_list[$value['order_id']]['member_id']]['mobile'];
            }
        }
        $list['commission'] = $memberInfo['commission'] ?: 0;//每日收益积分+退购转换积分
        $this->response->success($list);
    }

    /**
     * 分销佣金排行
     */
    public function commissionRanking()
    {
        $member_id = Request::invoke()->getMember('member_id');
        $list = MemberService::invoke()->getRankingList($member_id);
        $this->response->success($list);
    }

    /**
     * 功德排行 type =1 数量 =2 金额
     */
    public function meritList()
    {
        $page = input('get.page', 1);
        $limit = input('get.limit', 6);
        $type = input('get.type', 1);
        $memberInfo = Request::invoke()->getMember();
        $list = MemberService::invoke()->getMeritList($page, $limit, $type);
        $data = [
            'list' => $list,
        ];
        $data['info'] = [
            'member_id' => $memberInfo['member_id'],
            'avatar' => $memberInfo['avatar'],
            'nick' => $memberInfo['nick'],
            'merit_amount' => $memberInfo['merit_amount'],
            'merit_num' => $memberInfo['merit_num'],
        ];
        $this->response->success($data);
    }

    public function getLoginImage()
    {
        $info = SettingsService::invoke()->getInfo(1);
        $data = ['image' => $info['image']];
        $this->response->success($data);
    }

    /**
     * 找回密码-手机验证码获取
     */
    public function getRetrieveCode()
    {
        $mobile = input('post.mobile');
        $memberInfo = MemberService::invoke()->getMemberByMobile($mobile);
        if (!$memberInfo) {
            $this->response->error('用户不存在');
        }
        $data = MemberService::invoke()->getCode($memberInfo['mobile']);
        $time = time() - 60;
        if ($data && $data['time'] > $time) {
            $this->response->error('请稍后获取验证码');
        }
        //添加手机验证码业务逻辑
        $code = rand(100000, 999999);
        SmsService::sendSms($mobile, $code);
        MemberService::invoke()->saveCode($code, $memberInfo['mobile']);
        $this->response->success(['code' => $code], "获取成功");
    }

    /**
     * 找回密码-更新密码
     */
    public function retrieve()
    {
        $mobile = input('post.mobile');
        $password = input('post.password');
        $ret_password = input('post.ret_password');
        if ($password !== $ret_password) {
            $this->response->error('密码不一致');
        }
        $code = input('post.code');
        $memberInfo = MemberService::invoke()->getMemberByMobile($mobile);
        $data = MemberService::invoke()->getCode($memberInfo['mobile']);
        if (!$data) {
            $this->response->error('验证码已过期');
        }
        if ($code != $data['code']) {
            $this->response->error('验证码错误');
        }
        $memberService = MemberService::invoke();
        $memberService->savePassword($password, $memberInfo['member_id']);
        $this->response->success([], "更新成功");
    }

    /**
     * 小程序授权
     */
    public function getTokenByCode()
    {
        $code = input('post.code');
        $appid = $this->app->config->get('app.app_id');
        $secret = $this->app->config->get('app.app_secret');
        $url = 'https://api.weixin.qq.com/sns/jscode2session';//
        $url .= "?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
        $headers = array('Content-Type:application/json');
        $res = $this->httpGet($url, $headers);
        $res = json_decode($res, true);
        if (!empty($res['openid'])) {
            $member_data = [
                'openid' => $res['openid'],
                'session_key' => $res['session_key'],
            ];
            $rs = MemberService::invoke()->saveMember($member_data);
            $this->response->success($rs, "成功");
        } else {
            $this->response->error($res['errmsg']);
        }
    }

    public function getuserphonenumber()
    {
        $memberInfo = Request::invoke()->getMember();
        $code = input('post.code');
        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber';
        $url .= "?access_token=" . $memberInfo['access_token'];
        $header = [
            'Content-Type: application/json'
        ];
        $data_string = json_encode(['code' => $code]);
        $res = $this->request_post($url, $header, $data_string);
        $res = json_decode($res, true);
        var_dump($res);

    }

    private function request_post($url = '', $header = array(), $data_string = '')
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        } else {
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json',
                    'Content-Length: ' . strlen($data_string))
            );
        }
        $result = curl_exec($ch);
        return $result;
    }

    /**
     * 微信授权登录
     */
    public function getTokenLogin()
    {
        $code = input('post.code');
        $appid = $this->app->config->get('app.js_app_id');
        $secret = $this->app->config->get('app.js_app_secret');
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token';
        $url .= "?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
        $headers = array('Content-Type:application/json');
        $res = $this->httpGet($url, $headers);
        $res = json_decode($res, true);
        if (empty($res['openid'])) {
            $this->response->error($res['errmsg']);
        }
        $openid = $res['openid'];
        $access_token = $res['access_token'];
        $url2 = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
        $res2 = $this->httpGet($url2, $headers);
        $res2 = json_decode($res2, true);
        $member_data = [
            'js_openid' => $res['openid'],
            'access_token' => $res['access_token'],
            'unionid' => !empty($res2['unionid']) ? $res2['unionid'] : '',
            'avatar' => !empty($res2['headimgurl']) ? $res2['headimgurl'] : 'http://pray.veac.cn/storage/avatar.png',
        ];
        $token = MemberService::invoke()->saveJsOpenid($member_data);
        $this->response->success(['token' => $token], "登录成功");
    }

    public function httpGet($url, $header = array())
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!empty($header)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        }

        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }
}

